package com.clei.utils;

import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * jar util
 *
 * @author Y
 * @date 2024-03-14
 **/
public class JarUtil {

    public static void main(String[] args) {
        if (null == args || 0 == args.length) {
            PrintUtil.log("未指定jar路径");
            return;
        }
        print(args[0]);
    }

    /**
     * 打印
     *
     * @param jarPath jarPath
     */
    private static void print(String jarPath) {
        List<String> resources = getResources(jarPath);
        for (String resource : resources) {
            PrintUtil.println(resource);
        }
    }

    /**
     * jar resources
     *
     * @param url jarUrl
     * @return list
     */
    public static List<String> getResources(URL url) {
        try {
            JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
            JarFile jarFile = jarURLConnection.getJarFile();
            return getResources(jarFile);
        } catch (Exception e) {
            PrintUtil.log("getResources error url : ｛｝", url, e);
            return Collections.emptyList();
        }
    }

    /**
     * jar resources
     *
     * @param jarPath jarPath
     * @return list
     */
    public static List<String> getResources(String jarPath) {
        try (JarFile jarFile = new JarFile(jarPath)) {
            return getResources(jarFile);
        } catch (Exception e) {
            PrintUtil.log("getResources error filePath : ｛｝", jarPath, e);
            return Collections.emptyList();
        }
    }

    /**
     * jar resources
     *
     * @param jarFile jarFile
     * @return list
     */
    public static List<String> getResources(JarFile jarFile) {
        try (JarFile jf = jarFile) {
            Enumeration<JarEntry> entries = jf.entries();
            List<String> resList = new ArrayList<>();
            while (entries.hasMoreElements()) {
                JarEntry jarEntry = entries.nextElement();
                String name = jarEntry.getName();
                resList.add(name);
            }
            return resList;
        } catch (Exception e) {
            PrintUtil.log("getResources error jarFile : ｛｝", jarFile.getName(), e);
            return Collections.emptyList();
        }
    }
}
